export const useShopStore = defineStore('shop', () => {

  let shopGoodsList: any = $ref({})
  let shopDefaultStoreId: any = $ref('')

  // 控制是否监听商城购物车列表
  let isWatchShopGoodsList: any = $ref(0)
  const updatIsWatchShopGoodsList = () => {
    isWatchShopGoodsList++
  }

  const updateShopGoodsList = (payload) => {
    shopGoodsList = payload
  }

  const updateShopDefaultStoreId = (payload) => {
    shopDefaultStoreId = payload
  }
  // 获取购物车数据
  const getShopGoodsCarDataList = async (userId) => {
    const reqData = {
      method: 'post',
      data: {
        'storeId': shopDefaultStoreId,
        'trolleyType': 3,
      },
      headers: { UserId: userId },
    }
    const { data, status, error } = await Fetch('/qqyapi/order/trolley/renderTrolleyViewDto', reqData)
    if (status !== 200 || data.code !== 0) {
      return
    }
    if (data.code === 0) {
      updateShopGoodsList(data?.result)
      updatIsWatchShopGoodsList()
    }
  }
  // 一键清空购物车
  const allDelShopGoodsCar = async (userId) => {
    const reqData = {
      method: 'post',
      data: {
        'trolleyType': 3,
      },
      headers: { UserId: userId },
    }
    const { data, status, error } = await Fetch('/qqyapi/order/trolley/cleanTrolley', reqData)
    if (status !== 200 || data.code !== 0) {
      return
    }
    if (data.code === 0) {
      getShopGoodsCarDataList(userId)
      uni.showToast({
        title: '删除成功',
        icon: 'none',
      })
    }
  }
  // 购物车单个删除商品
  const singleDelShopGoodsCar = async (itemId, userId) => {
    const reqData = {
      method: 'post',
      data: {
        'delFlag': 1,
        'itemId': itemId,
        'trolleyType': 3,
      },
      headers: { UserId: userId },
    }
    const { data, status, error } = await Fetch('/qqyapi/order/trolley/reduce', reqData)
    if (status !== 200 || data.code !== 0) {
      return
    }
    if (data.code === 0) {
      getShopGoodsCarDataList(userId)
      uni.showToast({
        title: '删除成功',
        icon: 'none',
      })
    }
  }
  // 获取默认店铺的ID
  const getDefaultStore = async () => {
    const reqData = {
      method: 'post',
      headers: {
        AppType: 3,
      },
    }
    const { status, data, error } = await Fetch('/qqyapi/product/product/getDefaultSelfSupportShop', reqData)
    if (status !== 200 || data.code !== 0) {
      return
    }
    if (data.code === 0) {
      updateShopDefaultStoreId(data?.result.id)
    }
  }
  return {
    shopGoodsList: $$(shopGoodsList),
    isWatchShopGoodsList: $$(isWatchShopGoodsList),
    shopDefaultStoreId: $$(shopDefaultStoreId),
    updateShopGoodsList,
    updatIsWatchShopGoodsList,
    getShopGoodsCarDataList,
    allDelShopGoodsCar,
    singleDelShopGoodsCar,
    updateShopDefaultStoreId,
    getDefaultStore,
  }
}, { unistorage: { key: 'config-app' } })

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useShopStore, import.meta.hot))
